package cn.kgc.news.dao;

import java.sql.*;

public class BaseDao {
    public Connection conn = null;
    public PreparedStatement ps = null;
    public ResultSet rs = null;
    //获取连接
    public  boolean getConnection() {
        boolean flag = false;
        //连接数据库
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            String url = "jdbc:mysql://localhost:3306/kgcnews";
            conn = DriverManager.getConnection(url, "root", "123456");
            flag = true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }
    //查询数据
    public ResultSet excuteSelect(String sql,Object[]params){
        if(getConnection()){
            try {
                ps=conn.prepareStatement(sql);
                for (int i = 0; i <params.length ; i++) {
                    ps.setObject(i+1,params[i]);
                }
                rs=ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }
    //更新数据
    public int excuteUpdateRows(String sql,Object[]params){
        int ir=0;
        if(getConnection()){
            try {
                ps=conn.prepareStatement(sql);
                for (int i = 0; i <params.length ; i++) {
                    ps.setObject(i+1,params[i]);
                }
                ir=ps.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return ir;
    }
    //关闭连接
    public void closeConnection(){
        try {
            if(rs!=null) {
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
